<template>
  <div class="preview-wrap" @mousewheel="handerMousewheel">
    <div ref="previewRef" class="preview" style="overflow: hidden;">
      <!-- :src="imgList[currentIndex].url" -->
      <!-- https://img.sjgo365.com/fssc-client-minapp/test3.png -->
      <div
        v-if="getUrlType(imgList[currentIndex].url) === 'image'"
        @mousedown="handleMoveStart"
        :style="{ top: imgTop + 'px', left: imgLeft + 'px', transform: `scale(${imgScale}) rotateZ(${imgRotate}deg)` }"
        class="preview-content"
        >
          <div style="position: relative">
            <img
              class="ui-img"
              style="color: red"
              :style="{ width: imgSize.imageWidth + 'px', height: imgSize.imageHeight + 'px' }"
              :src="imgList[currentIndex].url"
              @click.stop="preventDefault"
            />
            <div class="area-tag" v-if="imgList[currentIndex].rect && !isHideRect"  :style="{ top: areaObj.top, left: areaObj.left, width: areaObj.width, height: areaObj.height, transform: `rotate(${imgList[currentIndex].rect.angle}deg)` }"></div>
          </div>
      </div>
      <iframe v-else :src="getFileSrc(imgList[currentIndex].url)" style="width:100%;height: 100%" :style="{ top: imgTop + 'px', left: imgLeft + 'px', transform: `rotateZ(${imgRotate}deg)` }" frameborder="no" border="0"></iframe>
      <!-- <img
        
        :src="imgList[currentIndex]"
        :style="{ top: imgTop + 'px', left: imgLeft + 'px', transform: `scale(${imgScale}) rotateZ(${imgRotate}deg)` }"
        object-fit="contain"
        @click.stop="preventDefault"
        @mousedown="handleMoveStart"
      /> -->
      <div class="preview-footer" @click.stop="preventDefault">
        <ul class="preview-footer-tools">
          <li v-if="imgList.length > 1" @click="handleCut('last')"><img src="../images/arrow-left.png" alt="" /></li>
          <li @click="handleRotate('left')"><img src="../images/refresh-left.png" alt="" /></li>
          <li v-if="getUrlType(imgList[currentIndex].url) === 'image'" @click="imgScale = 1"><img src="../images/real-size.png" alt="" /></li>
          <li @click="handleRotate('right')"><img src="../images/refresh-right.png" alt="" /></li>
          <li v-if="imgList.length > 1" @click="handleCut('next')"><img src="../images/arrow-right.png" alt="" /></li>
        </ul>
        <div v-if="imgList.length > 1" class="__ui_current_index">{{ currentIndex + 1 }}/{{ imgList.length }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import testPath from '../images/test2.jpg'
import {Base64} from 'js-base64'
export default {
  props: {
    imgList: {
      type: Array,
      default: () => []
    },
    form: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      png: testPath,
      currentImg: '', // 当前预览图片的url
      imgKey: '', // 图片所在的数据的key
      imgTop: 0, // 图片定位置top
      imgLeft: 0, // 图片定位置left
      startPageX: 0, // 按下鼠标时当前鼠标所在位置x
      startPageY: 0, // 按下鼠标时当前鼠标所在位置y
      imgScale: 1, // 图片缩放
      imgRotate: 0, // 图片旋转
      currentIndex: 0,
      isHideRect: false,
      areaObj: {
        width: 0,
        height: 0,
        left: 0,
        top: 0
      },
      imageWidth: '',
      imgSize: {}
    }
  },
  mounted() {

  },
  watch: {
    imgList(newVal) {
      if (newVal && newVal.length > 0) {
        this.currentImg = this.imgList[0].url
      }
    },
    form: {
      deep: true,
      immediate: true,
      handler: function (val)  {
        this.isHideRect = true
        this.getBaseImg().then(() => {
          this.isHideRect = false
          this.drawArea()
        })
      }
    },
    show: {
      handler(v) {
        // if (v) {
        //   document.body.style.overflow = 'hidden'
        //   document.addEventListener('mousemove', this.preventDefault, false)
        // } else {
        //   document.body.style.overflow = ''
        //   document.removeEventListener('mousemove', this.preventDefault, false)
        //   document.removeEventListener('mouseup', this.clearEvent, false)
        //   this.reset()
        // }
      },
      immediate: true
    },
    currentImg() {
      this.imgTop = 0
      this.imgLeft = 0
      this.imgScale = 1
      this.imgRotate = 0
    }
  },
  methods: {
    getBaseImg() {
      return new Promise((resolve) => {
        const myImg = new Image()
        myImg.src = this.imgList[this.currentIndex].url
        // myImg.src = this.png
        myImg.onload = () => {
          this.imageWidth = myImg.width
          this.imageUtil({ width: myImg.width, height: myImg.height })
          resolve()
        }
      })
    },
    imageUtil: function (e) {
      var imageSize = {};
      var originalWidth = e.width; // 图片原始宽
      var originalHeight = e.height; // 图片原始高
      var originalScale = originalHeight/originalWidth; //图片高宽比
      imageSize.originalWidth = originalWidth
      imageSize.originalHeight = originalHeight
      imageSize.originalScale = originalScale
      //获取屏幕宽高
      var windowWidth = this.$refs.previewRef.clientWidth;
      var windowHeight = this.$refs.previewRef.clientHeight;
      var windowscale = windowHeight/windowWidth;//屏幕高宽比
      if (originalScale < windowscale) { // 图片高宽比小于屏幕高宽比
        //图片缩放后的宽为屏幕宽
        imageSize.imageWidth = windowWidth;
        imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth;
      } else { // 图片高宽比大于屏幕高宽比
        //图片缩放后的高为屏幕高
        imageSize.imageHeight = windowHeight;
        imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight;
      }
      console.log(imageSize, 'imageSize')
      this.imgSize = imageSize
      return imageSize;
    },
    drawArea() {
      if (this.imgList[this.currentIndex].rect) {
        const tarRect = this.imgList[this.currentIndex].rect
        const widthRatio = this.imgSize.imageWidth / this.imgSize.originalWidth
        const heightRatio = this.imgSize.imageHeight / this.imgSize.originalHeight
        // item.left = item.rect.x * widthRatio
        // item.top = item.rect.y * heightRatio
        // item.width = item.rect.width * widthRatio
        // item.height = item.rect.height * heightRatio
        this.areaObj = {
          width: tarRect.width * widthRatio  + 'px',
          height: tarRect.height * heightRatio  + 'px',
          left: tarRect.x * widthRatio  + 'px',
          top: tarRect.y * heightRatio  + 'px'
        }
      }
    },
    getFileSrc(src) {
      if (import.meta.env.MODE == 'production') {
         src = src.replace('https://obs-cq.cucloud.cn', 'http://obs-cq-internal.cucloud.cn')
      }
      console.log(src, 'src')
      return `${import.meta.env.VITE_KK_FILE}?url=${encodeURIComponent(Base64.encode(src))}`
    },
    getUrlType(src) {
      let result = ''
      const type = src.replace(/.+\./g,'')
      if (type === 'png' || type === 'jpg' || type === 'jpeg') {
        result = 'image'
      } else {
        result = 'file'
      }
      return result
    },
    // 关闭时重置值
    reset() {
      // this.imgList = []
      // this.currentImg = ''
      // this.imgKey = ''
      // this.imgTop = 0
      // this.imgLeft = 0
      // this.startPageX = 0
      // this.startPageY = 0
      // this.imgScale = 1
      // this.imgRotate = 0
      // this.currentIndex = 0
    },
    // 旋转
    handleRotate(type) {
      if (type === 'left') {
        this.imgRotate -= 90
      } else {
        this.imgRotate += 90
      }
    },
    // 切换上一张或者下一张
    handleCut(type) {
      console.log(this.imgList.length, 'this.imgList.length')
      if (this.imgList.length < 2) return
      const currentIndex = this.currentIndex
      let targetIndex = null
      if (type === 'last') {
        if (currentIndex === 0) {
          targetIndex = this.imgList.length - 1
        } else {
          targetIndex = currentIndex - 1
        }
      }
      if (type === 'next') {
        if (currentIndex === this.imgList.length - 1) {
          targetIndex = 0
        } else {
          targetIndex = currentIndex + 1
        }
      }
      const targetItem = this.imgList[targetIndex]
      this.currentImg = targetItem.url
      this.$emit('swiperChange', targetItem)
      this.handleXScroll(targetIndex)
      this.currentIndex = targetIndex
      if (this.changeCallBack) {
        this.changeCallBack(targetIndex)
      }
    },
    // 使滚动条滚动到当前预览的那一张
    handleXScroll(index) {
      index = index < 4 ? 0 : index - 4
      const imgParentElement = document.querySelector('.preview-footer-thumbs')
      // const imgWrapElement = document.querySelector('#thumb-item-' + index)
      // imgParentElement.scrollLeft = imgWrapElement.offsetLeft
      if (this.changeCallBack) {
        this.changeCallBack(index)
      }
    },
    // 点击缩略图切换当前预览
    handleClickThumb(item, index) {
      const url = this.imgKey ? item[this.imgKey] : item
      this.currentImg = url
      this.currentIndex = index
      this.handleXScroll(index)
    },
    // 鼠标滚轮缩放图片
    handerMousewheel(e) {
      // 火狐浏览器为e.detail 其他浏览器均为e.wheelDelta
      if ((e.wheelDelta > 0 || e.detail > 0) && this.imgScale < 4) {
        this.imgScale += 0.1
      } else if ((e.wheelDelta < 0 || e.detail < 0) && this.imgScale > 0.5) {
        this.imgScale += -0.1
      }
    },
    // 按下鼠标开始移动图片
    handleMoveStart(e) {
      const { pageX, pageY } = e
      this.startPageX = pageX - this.imgLeft
      this.startPageY = pageY - this.imgTop
      document.addEventListener('mousemove', this.handleMore, false)
      document.addEventListener('mouseup', this.clearEvent, false)
      e.preventDefault()
    },
    // 移除事件
    clearEvent() {
      document.removeEventListener('mousemove', this.handleMore, false)
    },
    // 按住鼠标移动时的处理
    handleMore(e) {
      const { pageX, pageY } = e
      this.imgTop = pageY - this.startPageY
      this.imgLeft = pageX - this.startPageX
      e.preventDefault()
    },
    // 阻止默认行为
    preventDefault(e) {
      e.preventDefault()
    }
  }
}
</script>

<style lang="scss" scoped>
.preview-wrap {
  width: 100%;
  height: 100%;
  .area-tag{
    position: absolute;
    left: 0;
    bottom: 0;
    // width: 200px;
    // height: 200px;
    border: 2px solid red;
  }
  li {
    list-style: none;
  }

  .preview {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    &-content {
      position: relative;
      cursor: move;
      transition: 0.2s transform;
      max-height: 100vh;
      .ui-img{
        width: 100%;
        // height: 100%;
      }
    }
    &-footer {
      position: absolute;
      bottom: 20px;
      left: 50%;
      transform: translateX(-50%);
      &-tools {
        display: flex;
        justify-content: center;

        li {
          margin-right: 10px;
          padding: 10px;
          border-radius: 50%;
          background: rgba(110, 110, 110, 0.7);
          cursor: pointer;
          > img {
            display: block;
            width: 30px;
            height: 30px;
          }
          &:hover {
            i {
              color: #ef544e;
            }
          }
        }
      }

      &-thumbs {
        margin-top: 20px;
        max-width: 700px;
        overflow-x: auto;
        white-space: nowrap;

        .thumb-item {
          padding: 10px;
          margin-right: 10px;
          display: inline-block;
          background: rgba(102, 102, 102, 0.7);
          border-radius: 5px;
          cursor: pointer;
          img {
            width: 60px;
            height: 60px;
            object-fit: cover;
          }
          &.active {
            background: rgba(239, 84, 78, 0.7);
          }
        }
        &::-webkit-scrollbar {
          height: 10px;
        }

        &::-webkit-scrollbar-thumb {
          border-radius: 10px;
          -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          background: #d2d2d2;
          cursor: pointer;
        }

        &::-webkit-scrollbar-track {
          border-radius: 10px;
          background: #fff;
        }
      }
    }
  }
  .__ui_current_index{
    margin: 0 auto;
    text-align: center;
    width: auto;
    // display: flex;
    // align-items: center;
    color: rgb(110, 110, 110) ;
    // background: rgba(110, 110, 110, 0.7);
    padding: 0 12px;
    // border-radius: 8px;
  }
}
</style>
